<template>
  <div class="login-container">
    <!-- auto-complete属性实现自动填充默认值到输入框里 -->
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">
      <!-- <h3 class="title">员工管理系统</h3> -->
      <!-- 头像 -->
      <div class="avatar">
        <img v-if="avatarUrl===baseUrl || avatarUrl === baseUrl + 'null' || avatarUrl=== baseUrl + 'undefined'" src="../../assets/touxiang.jpg" class="avatarImg">
        <img v-else :src="avatarUrl" class="avatarImg">
      </div>
      <!-- 用户名 -->
      <el-form-item prop="username" size="small">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input v-model="loginForm.username" name="username" type="text" auto-complete="on" placeholder="username" @input="getAvatarUrl"/>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item prop="password" size="small">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :type="pwdType"
          v-model="loginForm.password"
          name="password"
          placeholder="password"
          @keyup.enter.native="handleLogin" />
        <span class="show-pwd" @click="showPwd">
          <svg-icon icon-class="eye" />
        </span>
      </el-form-item>
      <!-- 记住密码 -->
      <el-checkbox v-model="checked" style="margin-bottom: 5px">记住密码</el-checkbox>
      <!-- 登录 -->
      <el-form-item>
        <el-button :loading="loading" type="primary" style="width:100%;" @click.native.prevent="handleLogin">
          Sign in
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'

export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value.length < 3) {
        callback(new Error('用户名不能小于5位'))
      } else {
        callback()
      }
    }
    const validatePass = (rule, value, callback) => {
      if (value.length < 5) {
        callback(new Error('密码不能小于5位'))
      } else {
        callback()
      }
    }
    return {
      baseUrl: '',
      passwordtoken: '',
      checked: true,
      // 表单中的数据
      loginForm: {
        username: '',
        password: ''
      },
      // 登录规则
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePass }]
      },
      loading: false,
      pwdType: 'password',
      redirect: undefined
    }
  },
  computed: {
    ...mapGetters([
      'avatarUrl'
    ])
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  mounted() {
    console.log('mounted')
    console.log(document.cookie.length)
    this.baseUrl = process.env.API_BASEURL
    this.getCookie()
    if (this.loginForm.username.length !== 0) {
      // 触发vuex中的getAvatar事件
      this.$store.dispatch('GetAvatar', this.loginForm.username).then(() => {
        console.log('跳转到index页面')
      }).catch(() => {
        console.log('获取图片出错')
      })
    }
    console.log(this.HOST)
  },
  methods: {
    showPwd() {
      if (this.pwdType === 'password') {
        this.pwdType = ''
      } else {
        this.pwdType = 'password'
      }
    },
    // 设置cookie
    setCookie(c_name, c_pwd, exdays) {
      var exdate = new Date() // 获取时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays) // 保存的天数
      // 字符串拼接cookie
      window.document.cookie = 'username' + '=' + c_name + ';path=/;expires=' + exdate.toGMTString()
      window.document.cookie = 'password' + '=' + c_pwd + ';path=/;expires=' + exdate.toGMTString()
    },
    // 读取cookie
    getCookie: function() {
      if (document.cookie.length > 0) {
        var arr = document.cookie.split('; ')
        for (var i = 0; i < arr.length; i++) {
          var arr2 = arr[i].split('=')
          // 判断查找相对应的值
          if (arr2[0] === 'username') {
            this.loginForm.username = arr2[1]
          } else if (arr2[0] === 'password') {
            this.loginForm.password = 'remember'
            this.passwordtoken = arr2[1]
          }
        }
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          const data = {
            username: this.loginForm.username,
            password: this.loginForm.password
          }
          // 触发vuex中的Login事件
          if (this.passwordtoken !== null && this.passwordtoken.length !== 0 && data.password.startsWith('remember')) {
            data.password = this.passwordtoken
          }
          this.$store.dispatch('Login', data).then(() => {
            if (this.checked === true) {
              this.setCookie(this.loginForm.username, getToken(), 7)
            }
            this.loading = false
            // 重定向到登录成功页面即首页 /dashboard
            console.log('跳转到index页面')
            this.$router.push({ path: this.redirect || '/' })
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getAvatarUrl(data) {
      // 触发vuex中的getAvatar事件
      this.$store.dispatch('GetAvatar', data).then(() => {
      }).catch(() => {
        console.log('没有获取到头像')
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
$bg:#fff;
$light_gray:#000;

/* reset element-ui css */
.login-container {
  background: url("../../assets/bg_1.jpg") no-repeat;
  background-position: center;
  background-size: cover;
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;
    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      &:-webkit-autofill {
        -webkit-box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: rgb(0, 0, 0) !important;
      }
    }
  }
  .el-form-item {
    border: 1px solid rgba(0, 0, 0, 0.1);
    // background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    // color: #454545;
  }
}

</style>

<style rel="stylesheet/scss" lang="scss" scoped>
$bg:#fff;
$dark_gray:#889aa4;
$light_gray:#000;
.login-container {
  position: fixed;
  height: 100%;
  width: 100%;
  background-color: $bg;
  // background-image: url('../../assets/bg.jpg)';
  .login-form {
    position: absolute;
    left: 0;
    right: 0;
    width: 460px;
    max-width: 100%;
    padding: 35px 35px 15px 35px;
    margin: 180px auto;
    border: 1px solid #eaeaea;
    box-shadow: 0 0 25px #cac6c6;
    -webkit-border-radius: 5px;
    border-radius: 5px;
    -moz-border-radius: 5px;
    background-color: white;
  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }
  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }
  .title {
    font-size: 26px;
    font-weight: 400;
    color: $light_gray;
    margin: 0px auto 10px auto;
    text-align: center;
    font-weight: bold;
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .svg-icon{
    fill: black
  }
  .remember {
    margin: 0px 0px 35px 0px;
  }
}
.avatar {
  height: 120px;
  width: 120px;
  margin: 0px auto;
  margin-bottom: 25px
}
.avatarImg {
  height: 120px;
  width: 120px;
  border-radius: 60px;
}
</style>
